package space.jamestang.simpleci.server.handler

import io.ktor.server.application.Application
import io.ktor.server.request.receive
import io.ktor.server.response.respond
import io.ktor.server.routing.delete
import io.ktor.server.routing.get
import io.ktor.server.routing.post
import io.ktor.server.routing.put
import io.ktor.server.routing.routing
import kotlinx.coroutines.runBlocking
import org.ktorm.dsl.eq
import org.ktorm.entity.add
import org.ktorm.entity.removeIf
import org.ktorm.entity.sequenceOf
import org.ktorm.entity.toList
import org.ktorm.entity.update
import space.jamestang.simpleci.database
import space.jamestang.simpleci.schema.Project
import space.jamestang.simpleci.schema.Projects
import space.jamestang.simpleci.server.Data
import space.jamestang.simpleci.server.ERROR
import space.jamestang.simpleci.server.OK

fun Application.projectCRUD() {

    routing{
        get("/projects"){
            val projects = runBlocking{
                database.sequenceOf(Projects).toList()
            }
            call.respond(Data(data = projects))
        }
        post("/projects"){
            val project = call.receive<Project>()
            project.buildCommand = emptyList()
            project.environment = emptyList()
            val result = database.sequenceOf(Projects).add(project)
            if (result == 1){
                call.respond(OK)
            }else{
                call.respond(ERROR)
            }
        }
        put("/projects"){
            val project = call.receive<Project>()
            val result = database.sequenceOf(Projects).update(project)
            if (result == 1){
                call.respond(OK)
            }else{
                call.respond(ERROR)
            }
        }
        delete("/projects/{id}") {
            val id = call.pathParameters["id"]?: return@delete
            val result = database.sequenceOf(Projects).removeIf { projects -> projects.id eq id.toInt() }
            if (result == 1){
                call.respond(OK)
            }else{
                call.respond(ERROR)
            }
        }
    }
}